{% extends "services/services_base.html" %}
{% load i18n %}
{% load guardian_tags %}

{% block body %}
<div class="twocol">
  <h3><strong>{{service.title|default:service.name}}</strong></h3>
      <p><strong>{% trans "Type" %}:</strong> {{service.service_type}}</p>
      <p><strong>{% trans "URL" %}:</strong> {{service.base_url}}</p>
      <p><strong>{% trans "Abstract" %}:</strong> {{service.abstract}}</p>
      <p><strong>{% trans "Keywords" %}:</strong> {{ service.keywords.all|join:", " }}</p>
      <p><strong>{% trans "Contact" %}:</strong> <a href="{% url "profile_detail" service.owner.username %}">{{ service.owner }}</a></p>
      {% if service.type == 'WMS' and service.needs_authentication %}
        <p><strong>SERVICE NOTES:</strong> The service is accessed by Basic auth via the user <strong>{{service.username}}</strong></p>
      {% endif %}
    {% autoescape off %}
        <div id="harvestProgressWrapper" style="display:none;">
            <i class="fa fa-gear"></i> <i id="harvestProgressText"></i>
            <div class="progress" id="harvestProgressContainer">
                <div class="progress-bar" id="harvestProgressBar" role="progressbar"
                    style="width:0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
                    0%
                </div>
            </div>
        </div>
        <div id="resourcesContainer">
            {% if resources %}
                {% include "services/service_resources_partial.html" %}
            {% else %}
                <p>{% trans "No resources have been imported yet." %}</p>
            {% endif %}
        </div>
    {% if resources.paginator.num_pages > 1 %}
        <div class="row">
            <nav aria-label="importable resources pages">
                <ul class="pagination hidden-xs pull-right">
                    {% if resources.has_previous %}
                        <li><a id="previous" aria-label="Previous" href="?page={{ resources.previous_page_number }}">{% trans "previous" %}</a></li>
                    {% else %}
                        <li class="disabled"><a aria-label="Previous" href="#">{% trans "previous" %}</a></li>
                    {% endif %}
                    <li class="active"><a href="#">{{ resources.number }}/{{ resources.paginator.num_pages }}</a></li>
                    {% if resources.has_next %}
                        <li><a aria-label="{% trans "Next" %}" href="?page={{ resources.next_page_number }}">{% trans "next" %}</a></li>
                    {% else %}
                        <li class="disabled"><a aria-label="{% trans "Next" %}" href="#">{% trans "next" %}</a></li>
                    {% endif %}
                </ul>
            </nav>
        </div>
    {% endif %}
    {% endautoescape %}
    <div class="modal fade" data-backdrop="static" data-keyboard="false" id="progressModal" tabindex="-1" role="dialog" aria-labelledby="progressModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    {% trans "Connecting to service..." %}
                </div>
                <div class="modal-body">
                    <div class="progress" id="serviceRegisterProgress">
                        <div class="progress-bar progress-bar-striped progress-bar-info active" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%;">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>
{% endblock %}
{% block sidebar %}

    {% get_obj_perms request.user for service as "resource_perms" %}

    {% if can_add_resorces or "add_resourcebase" in resource_perms or "change_resourcebase_metadata" in resource_perms or "change_service_permissions" in resource_perms %}
    <ul class="list-group">
        <li class="list-group-item"><h3>{% trans "Manage" %}</h3></li>
        {% if "change_resourcebase_metadata" in resource_perms %}
            <li class="list-group-item"><a class="btn btn-default btn-md btn-block" href="{% url "edit_service" service.id %}">{% trans "Edit Service Metadata" %}</a></li>
        {% endif %}
        {% if can_add_resorces %}
            <li class="list-group-item"><a id="harvestResources" class="btn btn-default btn-md btn-block" href="{% url "harvest_resources" service.id %}">{% trans "Import Service Resources" %}</a></li>
        {% endif %}
        {% if "remove_service" in permissions_list or "delete_service" in permissions_list or 'delete_resourcebase' in permissions_list %}
            <li class="list-group-item"><a class="btn btn-default btn-md btn-block" href="{% url "remove_service" service.id %}">{% trans "Remove Service" %}</a></li>
        {% endif %}
      </ul>
    {% endif %}
{% endblock %}
{% block extra_script %}
{{ block.super }}
<script type="text/javascript">
    $(document).ready(function () {
        $('#harvestResources').on("click", function() {
            $("#progressModal").modal("show");
        });

        $('button[name^=retry]').on('click', function () {
            const resourceId = this.name.replace("retry-", "");
            const retryUrl = "/services/{{ service.id }}/harvest/" + resourceId;
            const retryForm = document.createElement('form');
            retryForm.setAttribute("method", "post");
            retryForm.setAttribute("action", retryUrl);
            const csrfInputElem = document.createElement("input");
            csrfInputElem.type = "hidden";
            csrfInputElem.name = "csrfmiddlewaretoken";
            csrfInputElem.value = "{{ csrf_token }}";
            retryForm.appendChild(csrfInputElem);
            document.body.appendChild(retryForm);
            retryForm.submit();
        });

        
    let lastStatus = null;
    let resourcesUpdated = false;

    function updateHarvestProgress() {
        $.get("{% url 'service_harvest_progress' service.id %}", function(data) {
            let progress = data.progress || 0;

            if (data.in_progress) {
                $("#harvestProgressWrapper").show();
                $("#harvestProgressText").text("Resource harvesting in progress...");
                $("#harvestProgressBar")
                    .css("width", progress + "%")
                    .attr("aria-valuenow", progress)
                    .text(Math.round(progress) + "%");
                resourcesUpdated = false; // reset flag while harvesting
            } else {
                $("#harvestProgressWrapper").hide();
                $("#harvestProgressText").text("");
                $("#harvestProgressBar")
                    .css("width", "0%")
                    .attr("aria-valuenow", 0)
                    .text("0%");

                // Trigger partial API exactly once when in-progress → finished
                if (lastStatus === "on-going" && !resourcesUpdated) {
                    $("#resourcesContainer").load("{% url 'service_resources_partial' service.id %}");
                    resourcesUpdated = true;
                }
            }

        lastStatus = data.status;
    });
}
    updateHarvestProgress();
    setInterval(updateHarvestProgress, 7000)
    });
</script>
{% endblock extra_script %}
